package root.electronclass.electronclass.home.widget

import androidx.lifecycle.*
import root.electronclass.electronclass.mvp.entity.Message
import root.electronclass.electronclass.mvp.entity.MessageDto
import root.electronclass.electronclass.mvp.entity.NoticeData
import root.electronclass.electronclass.ext.CoroutineExceptionHandler
import root.electronclass.electronclass.school.rep.SchoolRepository
import kotlinx.coroutines.launch

/**
 *@ClassName TODO
 *@Description TODO
 *@Author caofc
 *@Date 2023/3/31 23:25
 */
class MessageModel : ViewModel() {
    private val _data = MediatorLiveData<Pair<Int, List<Message>>>()
    val data: LiveData<Pair<Int, List<Message>>> = _data

    private val pageIndex = MutableLiveData(1)

    private var text: String = ""
    private var sendUserType: Int = 1
    private var type: Boolean = false


    /**
     * 加载班级通知
     */
    fun load(type: Boolean = this.type, text: String = this.text, sendUserType: Int = this.sendUserType, page: Int = (pageIndex.value ?: 1) + 1) {
        this.text = text
        this.type = type
        this.sendUserType = sendUserType
        pageIndex.value = page
        loadData(type, text, sendUserType)
    }

    private fun loadData(type: Boolean, text: String, sendUserType: Int) {
        viewModelScope.launch(CoroutineExceptionHandler() { pageIndex.value = ((pageIndex.value ?: 1) - 1).coerceAtLeast(1) }) {
            _data.value = pageIndex.value!! to SchoolRepository.message(MessageDto(type, text, sendUserType))
            pageIndex.value = (pageIndex.value ?: 1) + 1
        }
    }

    fun editData(item: NoticeData) {
        viewModelScope.launch(CoroutineExceptionHandler()) {
            SchoolRepository.updateNotice(item)
        }
    }

}